package cn.congine.wizarpos.mall.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.congine.wizarpos.mall.common.RespMessage;
import cn.congine.wizarpos.mall.model.ErpCarterOrder;
import cn.congine.wizarpos.mall.model.ErpProduct;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.Category;
import cn.congine.wizarpos.mall.model.open.CateringOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringOrderQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringReOrderDto;
import cn.congine.wizarpos.mall.model.open.CateringReOrderListQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringReOrderListQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderBindingOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderDto;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderListQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderMemberCardPayInput;
import cn.congine.wizarpos.mall.model.open.CateringSaleOrderMemberCardPayOutput;
import cn.congine.wizarpos.mall.model.open.CateringStageQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringStageQueryOutput;
import cn.congine.wizarpos.mall.model.open.CateringTableOrderStageInput;
import cn.congine.wizarpos.mall.model.open.CateringTableReservedQueryInput;
import cn.congine.wizarpos.mall.model.open.CateringTableReservedQueryOutput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.GetTabelIdInput;
import cn.congine.wizarpos.mall.model.open.GetTabelIdOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncInput;
import cn.congine.wizarpos.mall.model.open.ProductCategorySyncOutput;
import cn.congine.wizarpos.mall.model.open.Table;
import cn.congine.wizarpos.mall.model.open.TableOrder;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.tenpay.util.MD5Util;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.Utils;
import cn.congine.wizarpos.mall.utils.WxSignUtil;
import cn.congine.wizarpos.mall.vo.CateringReOrderView;
import cn.congine.wizarpos.mall.vo.ProductView;
import net.sf.json.JSONArray;

@Controller
@RequestMapping(value = "/catering")
public class CateringAction
{
	private Logger logger = Logger.getLogger(CateringAction.class);

	@Autowired
	private WPosHttpClient wPosHttpClient;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;

	@Resource(name = "messageSource")
	private MessageSource messageSource;

	/**
	 * 先扫二维码再到menu页 add xudongdong
	 * 
	 * @param openId
	 * @param mid
	 * @param httpRequest
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/scan2menu")
	public ModelAndView ys(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/scan2menu");
		tmpUrl.append("?mid=").append(mid);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appId = result.get("appid");
			// 微信 js config 签名
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.put("mid", mid);
			data.putAll(ret);
			data.put("appId", appId);
			data.putAll(ret);
		}
		data.put("currentTime", new Date());

		return new ModelAndView("yuding/scan2menu", data);
	}

	/**
	 * 餐饮立即点单（先到menu页下单前在扫码）
	 * 
	 * @return
	 */
	@RequestMapping("/menuview")
	public ModelAndView menuView()
	{
		return new ModelAndView("yuding/menu");
	}

	/**
	 * 获取可预订的时间段
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/yudingTable", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView getTableStage(
			@RequestParam(value = "mid", required = true) String mid,
			Model model, HttpServletRequest httpRequest)
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		// 请求开放平台 获取 餐厅时段信息
		CateringStageQueryInput input = new CateringStageQueryInput();
		input.setMid(mid);
		CateringStageQueryOutput ouptut = (CateringStageQueryOutput) wizarposOpenRestClient
				.post(input, "/catering/stage/query",
						CateringStageQueryOutput.class);

		model.addAttribute("stageList", ouptut.getResult());
		model.addAttribute("mid", mid);

		Utils.setSessionToken(httpRequest);

		// 请求微信 js api的完整页面地址
		String baseUrl = getBaseURL(httpRequest);
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/yudingTable");
		tmpUrl.append("?mid=");
		tmpUrl.append(mid);

		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));

		return new ModelAndView("yuding/yuding", data);
	}

	/**
	 * 根据日期和时段，选择空闲的桌号
	 * 
	 * @param mid
	 * @param date
	 * @param timeStage
	 * @return
	 */
	@RequestMapping(value = "/getUnUsedTables", method = RequestMethod.GET)
	public @ResponseBody List<Table> getUnusedTables(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "selectDate", required = true) String selectDate,
			@RequestParam(value = "selectStageId") String selectStageId,
			@RequestParam(value = "nonceStr") String nonceStr)
	{
		// 根据日期选择可供预定的桌号
		CateringTableReservedQueryInput input = new CateringTableReservedQueryInput();
		input.setMid(mid);
		input.setDate(selectDate);
		input.setTimeId(selectStageId);
		CateringTableReservedQueryOutput output = (CateringTableReservedQueryOutput) wizarposOpenRestClient
				.post(input, "/catering/table/unused",
						CateringTableReservedQueryOutput.class);
		;
		if (output != null && output.getResult() != null)
		{
			return output.getResult();
		}
		return null;
	}

	/**
	 * 餐桌预订
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/yudingsubmit")
	@ResponseBody
	public RespMessage yudingSubmit(
			@RequestParam(value = "date", required = true) String date,
			@RequestParam(value = "time_id", required = true) String time_id,
			@RequestParam(value = "table_id", required = true) String table_id,
			@RequestParam(value = "mans_num", required = true) String mans_num,
			@RequestParam(value = "tel", required = true) String tel,
			@RequestParam(value = "linker", required = true) String linker,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "token", required = true) String token,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException
	{
		RespMessage res = new RespMessage();
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(cardId) || StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			res.setCode(2);
			return res;
		}
		SimpleDateFormat old = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");

		String nowStr = sf.format(new Date());
		String oldStr = "1";
		try
		{
			oldStr = sf.format(old.parse(date));
		} catch (ParseException e1)
		{
			e1.printStackTrace();
		}
		Integer oldInteger = Integer.valueOf(oldStr);
		Integer nowInteger = Integer.valueOf(nowStr);

		if (oldInteger - nowInteger < 0)
		{
			res.setCode(1);
			res.setMessage("请选择今天及今天以后的日期");
			return res;
		}
		if (oldInteger - nowInteger == 0)
		{
			CateringTableOrderStageInput input = new CateringTableOrderStageInput();
			input.setMid(mid);
			input.setId(time_id);
			CommonResultOutput output = (CommonResultOutput) wizarposOpenRestClient
					.post(input, "/catering/stage/detail",
							CommonResultOutput.class);
			String range = ((Map<String, Object>) output.getResult()).get(
					"stageRange").toString();

			Calendar cal = Calendar.getInstance();
			Integer hour = cal.get(Calendar.HOUR_OF_DAY);
			Integer min = cal.get(Calendar.MINUTE);
			String timeRange = "";
			if (range.startsWith("-"))
			{
				timeRange = range.split("-")[1];
			} else if (!range.startsWith("-") && !range.endsWith("-"))
			{
				timeRange = range.split("-")[1];
			}
			if (!"".equals(timeRange))
			{
				String[] timeArr = timeRange.split(":");
				Integer endHour = Integer.valueOf(timeArr[0]);
				Integer endMin = Integer.valueOf(timeArr[1]);
				if (endHour < hour)
				{
					res.setCode(1);
					res.setMessage("请选择当前时间以后的时间段");
					return res;
				}
				if (endHour == hour)
				{
					if (endMin < min)
					{
						res.setCode(1);
						res.setMessage("请选择当前时间以后的时间段");
						return res;
					}
				}
			}
		}
		// 判断是否重复提交
		// if (Utils.isRepeatSubmit(httpRequest, token)) {
		// res.setCode(1);
		// res.setMessage("请勿重复提交");
		// return res;
		// }

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("reOrderDate", date);
		json.put("reOrderName", linker);
		json.put("reOrderNum", mans_num);
		json.put("reOrderPhone", tel);
		json.put("reOrderTimeId", time_id);
		json.put("reAmount", "0");
		JSONArray arr = new JSONArray();
		arr.add(table_id);
		json.put("tableList", arr);
		json.put("openId", openId);
		json.put("url", getBaseURL(httpRequest) + "/catering/yudinginfo?mid="
				+ mid + "&orderId=");

		JSONObject respJson = null;
		try
		{
			System.out.println("");
			System.out.println("-----/catering/reserve/table----" + time_id);
			System.out.println("");
			respJson = wPosHttpClient.postOpen("/catering/reserve/table", json);
		} catch (Exception e)
		{
			logger.error("请求开放接口，预订餐台失败");
			res.setCode(1);
			res.setMessage("请求开放接口，预订餐台失败");
			return res;
		}

		String code = respJson.getString("code");
		System.out.println("");
		System.out.println("-----code----" + code);
		System.out.println("");

		if ("0".equals(code))
		{
			String reOrderId = respJson.getJSONObject("result").getString(
					"reOrderId");

			// 记录绑定信息
			CateringOrderBindingInput input = new CateringOrderBindingInput();
			input.setMid(mid);
			input.setCardId(cardId);
			input.setOrderId(reOrderId);
			CateringOrderBindingOutput ouptut = (CateringOrderBindingOutput) wizarposOpenRestClient
					.post(input, "/catering/order/binding",
							CateringOrderBindingOutput.class);
			res.setCode(0);
			res.setObj(reOrderId);
			return res;
		} else
		{
			res.setCode(1);
			res.setMessage(respJson.getString("message"));
			return res;
		}
	}

	@RequestMapping("/yudingView")
	public ModelAndView yudingView(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderId", required = true) String orderId,
			HttpServletRequest httpRequest)
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		return new ModelAndView("yuding/yudingok").addObject("mid", mid)
				.addObject("orderId", orderId);
	}

	/**
	 * 餐桌预订详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/yudinginfo")
	public ModelAndView yudingInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest, Model model) throws Exception
	{

		CateringOrderQueryInput cateringOrderQueryInput = new CateringOrderQueryInput();
		cateringOrderQueryInput.setMid(mid);
		cateringOrderQueryInput.setReOrderId(orderId);
		CateringOrderQueryOutput cateringOrderQueryOutput = (CateringOrderQueryOutput) wizarposOpenRestClient
				.post(cateringOrderQueryInput, "/catering/reorder/query",
						CateringOrderQueryOutput.class);
		List<TableOrder> tableOrderList = cateringOrderQueryOutput.getResult();
		TableOrder tableOrder = tableOrderList.get(0);
		ErpCarterOrder erpCarterOrder = new ErpCarterOrder();
		// 截取显示单号
		erpCarterOrder.setShowOrderId(Function.getShowWxOrderNo(tableOrder
				.getOrderId()));
		// 转换显示金额
		erpCarterOrder.setOrderAmount(Utils.formatAmount(tableOrder
				.getReAmount()));
		// 转换显示时段
		erpCarterOrder.setStageId(tableOrder.getReOrderTimeRange());
		// 转换显示餐桌
		List<Table> tableList = tableOrder.getTableList();
		Table table = tableList.get(0);
		erpCarterOrder.setShowCreateTime(tableOrder.getCreateTime());
		erpCarterOrder.setOrderDate(tableOrder.getReOrderDate());
		erpCarterOrder
				.setAuditFlag(Integer.parseInt(tableOrder.getAuditFlag()));
		erpCarterOrder.setOrderMansNum(tableOrder.getOrderMansNum());
		erpCarterOrder.setOrderTel(tableOrder.getReOrderPhone());
		erpCarterOrder.setOrderLinker(tableOrder.getReOrderName());
		erpCarterOrder.setTableId(table.getTableId());
		if (table != null && table.getTableName() != null)
		{
			erpCarterOrder.setShowTable(table.getTableName());
		} else
		{
			erpCarterOrder.setShowTable(table.getTableCode());
		}
		// 转换订单显示用状态
		switch (erpCarterOrder.getAuditFlag())
		{
		case 0:
			erpCarterOrder.setShowStatus("审核中");
			break;
		case 1:
			erpCarterOrder.setShowStatus("预定已接受");
			break;
		case 2:
			String status = "预定已拒绝";
			String reason = erpCarterOrder.getRejectReason();
			if (!StringUtils.isEmpty(reason))
			{
				status += ", 原因：" + reason;
			}
			erpCarterOrder.setShowStatus(status);
			break;
		}

		model.addAttribute("order", erpCarterOrder);
		model.addAttribute("mid", mid);

		return new ModelAndView("yuding/yudinginfo");
	}

	/**
	 * 呼叫服务，通知商家，1呼叫加水，2呼叫买单，3提醒已经点单
	 * 
	 * @param table_id
	 * @param openId
	 * @param mid
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/callwaiter")
	public @ResponseBody String callWaiter(
			@RequestParam(value = "flag", required = true) String flag,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid)
			throws UnsupportedEncodingException
	{
		// 校验餐桌是否是开桌状态
		Boolean isUsing = wPosHttpClient.isTableUsing(mid, tableId);
		if (!isUsing)
		{
			return "2";
		}

		// pos消息提醒推送
		StringBuffer msg = new StringBuffer();
		if ("1".equals(flag))
		{
			msg.append("需要加水");
		} else if ("2".equals(flag))
		{
			msg.append("需要买单");
		} else if ("3".equals(flag))
		{
			msg.append("已经点餐");
		}
		JSONObject param = new JSONObject();
		param.put("mid", mid);
		param.put("sendMessage", msg);
		param.put("tableId", tableId);
		try
		{
			wPosHttpClient.postOpen("/catering/service/call", param);
		} catch (Exception e)
		{
			// 消息推送失败
			logger.error("推送呼叫服务消息失败，餐桌ID = " + tableId);
			logger.error(e);
			return "1";
		}

		return "0";
	}

	/**
	 * 
	 * @param token
	 * @param tableId
	 * @param openId
	 * @param mid
	 * @param orderNum
	 * @param sum
	 * @param orderDetail
	 * @param reOrderId
	 *            预订单id
	 * @param httpRequest
	 * @param attributes
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/submitmenu")
	@ResponseBody
	public RespMessage submitMenu(
			@RequestParam(value = "token", required = true) String token,
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			@RequestParam(value = "remark", required = false) String remark,// add
																			// xudongdong
			@RequestParam(value = "scanFlag", required = true) String scanFlag,// add
																				// xudongdong
			HttpServletRequest httpRequest) throws UnsupportedEncodingException
	{

		logger.info("submitmenu");

		RespMessage res = new RespMessage();
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(cardId) || StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			res.setCode(2);
			return res;
		}

		logger.info("cardId=" + cardId);

		if (reOrderId == null || reOrderId.isEmpty())
		{// TODO 是否查看有无预订单
			// Object stageId = erpTableOrderStageService.getCurrentStage(mid);
			// if (stageId != null) {
			// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			// Date today = null;
			// try {
			// today = format.parse(format.format(new Date()));
			// } catch (ParseException e) {
			// e.printStackTrace();
			// }
			// reOrderId = (String)erpCarterOrderService.getReOrderId(mid,
			// today,
			// stageId.toString(), tableId);
			// }
		} else
		{
			CateringOrderQueryInput input = new CateringOrderQueryInput();
			input.setMid(mid);
			input.setReOrderId(reOrderId);
			CateringOrderQueryOutput ouptut = (CateringOrderQueryOutput) wizarposOpenRestClient
					.post(input, "/catering/reorder/query",
							CateringOrderQueryOutput.class);
			List<TableOrder> tableOrderList = ouptut.getResult();
			if (tableOrderList.size() != 0
					&& !"1".equals(tableOrderList.get(0).getAuditFlag())
					&& !"0".equals(tableOrderList.get(0).getStatus()))
			{
				// 接受了的预订单，且未开桌的预定才可以在线点单
				res.setCode(1);
				res.setMessage("预定已经失效");
				return res;
			}
		}

		// 请求开放平台获取桌号
		if ("1".equals(scanFlag))
		{
			GetTabelIdInput getTabelIdInput = new GetTabelIdInput();
			getTabelIdInput.setMid(mid);
			getTabelIdInput.setTicketId(MD5Util.MD5Encode(tableId, "UTF-8"));
			GetTabelIdOutput getTabelIdOutput = (GetTabelIdOutput) wizarposOpenRestClient
					.post(getTabelIdInput, "/dzx/getTabelId",
							GetTabelIdOutput.class);
			if (getTabelIdOutput != null
					&& "0".equals(getTabelIdOutput.getCode())
					&& getTabelIdOutput.getResult() != null)
			{
				tableId = getTabelIdOutput.getResult().getTabelId();
			} else
			{
				logger.error("请求开放平台获取桌号失败");
				res.setCode(1);
				res.setMessage("系统错误，点餐失败。");
				return res;
			}
		}

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", null);
		json.put("reOrderId", reOrderId);
		JSONArray arr = new JSONArray();
		arr.add(tableId);
		json.put("tableId", arr);
		json.put("orderType", "1");// 堂吃
		json.put("orderSource", "2");// 微信订单
		json.put("status", "0");
		json.put("amount", sum);
		json.put("orderNum", orderNum);
		json.put("orderDetail", JSON.parseArray(orderDetail));
		json.put("print", true);
		json.put("remark", URLDecoder.decode(remark, "UTF-8"));
		json.put("openId", openId);

		// 请求开放平台获取appId
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefOuptut = (MerchantDefQueryOutput) wizarposOpenRestClient
				.post(merchantDefQueryInput, "/merchantdef/info",
						MerchantDefQueryOutput.class);
		if (merchantDefOuptut != null
				&& "0".equals(merchantDefOuptut.getCode()))
		{
			MerchantDef merchant = merchantDefOuptut.getResult();
			StringBuffer url = new StringBuffer(
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
			url.append(merchant.getWeixinAppId());
			url.append("&redirect_uri=http%3a%2f%2f");
			url.append(messageSource.getMessage(SysConstants.SERVICE_DNS, null,
					Locale.ENGLISH));
			String path = httpRequest.getContextPath();
			path = path.replace("/", "");
			url.append("%2f" + path +"%2foauth%2fcatering_menuinfo&response_type=code&scope=snsapi_base&state=");
			url.append(mid);
			url.append("ORDERID");
			json.put("url", url.toString());
		}
		JSONObject respJson = null;
		try
		{
			respJson = wPosHttpClient.postOpen("/catering/saleorder/submit",
					json);
		} catch (Exception e)
		{
			// 消息推送失败
			logger.error("点餐失败，餐桌ID = " + tableId);
			res.setCode(1);
			res.setMessage("系统错误，点餐失败。");
			return res;
		}

		String code = respJson.getString("code");
		if ("0".equals(code) || "60032".equals(code))
		{
			String orderId = respJson.getJSONObject("result").getString(
					"orderId");

			// 记录绑定信息
			CateringSaleOrderBindingInput input = new CateringSaleOrderBindingInput();
			input.setMid(mid);
			input.setCardId(cardId);
			input.setSaleOrderId(orderId);
			CateringSaleOrderBindingOutput ouptut = (CateringSaleOrderBindingOutput) wizarposOpenRestClient
					.post(input, "/catering/saleorder/binding",
							CateringSaleOrderBindingOutput.class);

			// if (Utils.isRepeatSubmit(httpRequest, token)) {
			// res.setCode(1);
			// res.setMessage("请勿重复提交");
			// return res;
			// }
			res.setCode(0);
			res.setObj(orderId);
			return res;
		} else
		{
			if ("60025".equals(code))
			{
				res.setCode(1);
				res.setMessage("桌子不可用，请找服务员点单");
				return res;
			}
			if ("60035".equals(code))
			{
				res.setCode(1);
				res.setMessage("桌子已经开台，请在找服务员点单");
				return res;
			}
			res.setCode(1);
			res.setMessage(respJson.getString("message"));
			return res;
		}
	}

	@RequestMapping("/menuOkView")
	public ModelAndView menuOkView(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "carterSaleOrderId", required = true) String carterSaleOrderId,
			HttpServletRequest httpRequest)
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		return new ModelAndView("yuding/menuok").addObject("mid", mid)
				.addObject("carterSaleOrderId", carterSaleOrderId);
	}

	/**
	 * 点单明细
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/menudetail")
	public ModelAndView menuDetail(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "orderNum", required = true) String orderNum,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderDetail", required = true) String orderDetail,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			HttpServletRequest httpRequest) throws IOException
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		com.alibaba.fastjson.JSONArray detailArray = JSON
				.parseArray(orderDetail);
		List<ProductView> list = new ArrayList<ProductView>();
		
		for (int i = 0; i < detailArray.size(); i++) {
			JSONObject detail = detailArray.getJSONObject(i);
			ProductView pv = new ProductView();
			pv.setId(detail.getString("id"));
			pv.setName(URLDecoder.decode(detail.getString("name"), "UTF-8"));
			pv.setPrice(detail.getString("price"));
			pv.setNum(detail.getInteger("qty"));
			pv.setCode(detail.getString("code"));
			pv.setDesc(detail.getString("productRemark"));
			list.add(pv);
		}
		// 点餐数量
		int productsNum = detailArray.size();
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/menudetail");
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);

		String timestamp = null;
		String noncestr = null;
		String signature = null;
		String appId = null;

		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			appId = result.get("appid");
			// 微信 js config 签名
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			timestamp = ret.get("timestamp");
			noncestr = ret.get("noncestr");
			signature = ret.get("signature");
		}

		Utils.setSessionToken(httpRequest);
		return new  ModelAndView("yuding/menudetail")
			.addObject("products", list)
			.addObject("sum", sum)
			.addObject("orderDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
			.addObject("productsNum", productsNum)
			.addObject("tableId", tableId)
			.addObject("orderNum", orderNum)
			.addObject("order", "")
			.addObject("mid", mid)
			.addObject("reOrderId", reOrderId)
			.addObject("timestamp", timestamp)
			.addObject("noncestr", noncestr)
			.addObject("signature", signature)
			.addObject("appId", appId);
	}

	@RequestMapping("/menudetailview")
	public ModelAndView menuDetailView()
	{
		return new ModelAndView("yuding/menudetail");
	}

	/**
	 * 点单详情
	 * 
	 * @param mid
	 * @param openId
	 * @param orderId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/menuinfo")
	public ModelAndView menuInfo(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws UnsupportedEncodingException
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		if (StringUtils.isEmpty(openId) || StringUtils.isEmpty(cardId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		JSONObject param = new JSONObject();
		param.put("mid", mid);
		param.put("orderId", orderId);
		JSONObject orderJson = null;
		try
		{
			orderJson = wPosHttpClient.postOpen("/catering/saleorder/query",
					param);
		} catch (Exception e)
		{
			// 消息推送失败
			logger.error("餐饮订单查询失败，单号：" + orderId);
			return new ModelAndView("error").addObject("err_message", "系统错误。");
		}

		if ("0".equals(orderJson.getString("code")))
		{
			com.alibaba.fastjson.JSONArray tickets = null;
			JSONObject ticketJson = wPosHttpClient.getCashTickets(openId, mid,
					cardId);
			if (ticketJson.getIntValue("code") == 0)
			{
				tickets = ticketJson.getJSONArray("result");// 代金券
				for (int i = 0; i < tickets.size(); i++)
				{
					JSONObject obj = tickets.getJSONObject(i);
					obj.put("balance",
							Utils.formatAmount(obj.getString("balance")));
				}
			}
			// 若未填写订单备注，则页面显示无
			if (StringUtils.isEmpty(orderJson.getJSONObject("result")
					.getString("remark")))
			{
				orderJson.getJSONObject("result").put("remark", "无");
			}

			return new ModelAndView("yuding/menuinfo").addObject("mid", mid)
					.addObject("orderId", orderId)
					.addObject("order", orderJson.getJSONObject("result"))
					.addObject("cashList", tickets).addObject("cardId", cardId);
		} else
		{
			return new ModelAndView("error").addObject("err_message",
					orderJson.getString("message"));
		}
	}

	/**
	 * 去支付
	 * 
	 * @param orderId
	 * @param openId
	 * @param mid
	 * @param payType
	 *            0 微信支付 1会员卡支付
	 * @param ticketId
	 *            代金券
	 * @return
	 */
	@RequestMapping(value = "/topay")
	@ResponseBody
	public RespMessage topay(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "sum", required = true) String sum,
			@RequestParam(value = "payType", required = false) String payType,
			@RequestParam(value = "ticketInfoIds", required = false) String ticketInfoIds,
			HttpServletRequest httpRequest)
	{
		RespMessage res = new RespMessage();
		String cardNo = (String) httpRequest.getSession().getAttribute("mrtCardNo");
		if (StringUtils.isEmpty(cardNo))
		{// session过期，跳转到登录注册页面
			res.setCode(2);
			return res;
		}

		StringBuffer url = null;
		// 请求开放平台获取appId
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput merchantDefOuptut = (MerchantDefQueryOutput) wizarposOpenRestClient
				.post(merchantDefQueryInput, "/merchantdef/info",
						MerchantDefQueryOutput.class);
		if (merchantDefOuptut != null
				&& "0".equals(merchantDefOuptut.getCode()))
		{
			MerchantDef merchant = merchantDefOuptut.getResult();
			url = new StringBuffer(
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
			url.append(merchant.getWeixinAppId());
			url.append("&redirect_uri=http%3a%2f%2f");
			url.append(messageSource.getMessage(SysConstants.SERVICE_DNS , null,
					Locale.ENGLISH));
			String path = httpRequest.getContextPath();
			path=path.replace("/", "");
			url.append("%2f"+ path +"%2foauth%2fcatering_menuinfo&response_type=code&scope=snsapi_base&state=");
			url.append(mid);
			url.append("ORDERID");
		}
		
		CateringSaleOrderMemberCardPayInput memberCardPayInput = new CateringSaleOrderMemberCardPayInput();					
		memberCardPayInput.setMid(mid);
		memberCardPayInput.setOrderId(orderId);
		memberCardPayInput.setAmount(sum);
		if (!StringUtils.isEmpty(ticketInfoIds)) {
			memberCardPayInput.setTicketInfoIds(Arrays.asList(ticketInfoIds.split(",")));
		}
		memberCardPayInput.setCardNo(cardNo);
		memberCardPayInput.setPrint(true);
		if (url != null) {
			memberCardPayInput.setUrl(url.toString());
		}
		CateringSaleOrderMemberCardPayOutput memberCardPayOutput =  (CateringSaleOrderMemberCardPayOutput) wizarposOpenRestClient.post(memberCardPayInput, "/catering/memberCardPay", CateringSaleOrderMemberCardPayOutput.class);
		if (memberCardPayOutput == null) {
			logger.error("餐饮订单会员卡支付失败，单号：" + orderId);
			res.setCode(1);
			res.setMessage("系统异常");
			return res;				
		} else if (SysConstants.OPEN_SUCCESS.equals(memberCardPayOutput.getCode())) {
			CateringSaleOrderMemberCardPayOutput.Result result = memberCardPayOutput.getResult();
			if (result != null) {
				// 推送管家号收款模板消息
				wPosHttpClient.pushHouseKeeperPaymentMsg(mid, result.getTranLogId());				
			}
			res.setObj(orderId);
			return res;
		} else if ("60010".equals(memberCardPayOutput.getCode())) { // 会员卡余额不足
			res.setCode(-1);
			res.setMessage(memberCardPayOutput.getMessage());
			res.setObj(orderId);
			return res;							
		} else {
			logger.error("code：" + memberCardPayOutput.getCode());
			logger.error("message：" + memberCardPayOutput.getMessage());
			res.setCode(1);
			return res;						
		}
	}

	@RequestMapping("/okView")
	public ModelAndView okView(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "orderId", required = true) String orderId,
			HttpServletRequest httpRequest)
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		return new ModelAndView("yuding/payok").addObject("mid", mid)
				.addObject("orderId", orderId);
	}

	/**
	 * 进入点餐
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/tomenu", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toMenu(
			@RequestParam(value = "tableId", required = false) String tableId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "reOrderId", required = false) String reOrderId,
			HttpServletRequest httpRequest) {	
		String openId = (String) httpRequest.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login?mid="+mid);
		}	
		
		Map<String, Object> data = new HashMap<String, Object>();
		ProductCategorySyncInput productCategorySyncInput = new ProductCategorySyncInput();
		productCategorySyncInput.setMid(mid);
		ProductCategorySyncOutput productCategorySyncOutput = (ProductCategorySyncOutput) wizarposOpenRestClient
				.post(productCategorySyncInput, "/product/category",
						ProductCategorySyncOutput.class);

		List<Category> categoryList = productCategorySyncOutput
				.getResult();

		Map<String, Object> products = new HashMap<String, Object>();
		for (Category category : categoryList)
		{
			String categoryId = category.getId();
			String categoryCode = category.getCode();

			MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
			merchandiseSyncInput.setMid(mid);
			merchandiseSyncInput.setCategoryId(categoryId);
			merchandiseSyncInput.setPageNo("1");
			MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
					.post(merchandiseSyncInput, "/product/merchandise",
							MerchandiseSyncOutput.class);

			List<Merchandise> productListTemp = merchandiseSyncOutput
					.getResult();
			List<ErpProduct> productList = new ArrayList<ErpProduct>();
			// 处理价格分-元，图片路径
			for (Merchandise prt : productListTemp)
			{
				ErpProduct ep = new ErpProduct();
				ep.setId(prt.getProductId());
				ep.setCode(prt.getCode());
				ep.setName(prt.getName());
				ep.setPrice(prt.getPrice());
				ep.setShowMemPrice(prt.getMemberPrice());
				if ("".equals(prt.getPicUrl()))
				{
					ep.setPicUrl(SysConstants.DEFAULT_PICTURE);
				} else {
					ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl().split(",")[0], 150, 150));
				}
				ep.setProductAtts(prt.getProductAtts());
				productList.add(ep);
			}

			products.put("topten" + categoryCode, productList);
		}
		// 从session中获取会员卡编号
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");

		// 请求微信 js api的完整页面地址
		String baseUrl = getBaseURL(httpRequest);
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/tomenu");
		tmpUrl.append("?mid=");
		tmpUrl.append(mid);
		if (!StringUtils.isEmpty(reOrderId))
		{
			tmpUrl.append("&reOrderId=");
			tmpUrl.append(reOrderId);
		}
		if (!StringUtils.isEmpty(tableId))
		{
			tmpUrl.append("&tableId=");
			tmpUrl.append(tableId);
		}

		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}

		data.put("dns", messageSource.getMessage(SysConstants.SERVICE_DNS, null,
				Locale.ENGLISH));

		return new ModelAndView("yuding/menu", data)
				.addObject("products", products)
				.addObject("categoryList", categoryList).addObject("mid", mid)
				.addObject("tableId", tableId)
				.addObject("reOrderId", reOrderId).addObject("cardId", cardId);
	}

	private String getBaseURL(HttpServletRequest httpRequest)
	{
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		return baseUrl;
	}

	/**
	 * 下一页菜品
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/moreProduct", method = RequestMethod.GET)
	public @ResponseBody List<ErpProduct> moreProduct(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "category", required = true) String category,
			@RequestParam(value = "pageIndex", required = true) int pageIndex)
	{
		String categoryCode = category.substring(6);
		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();
		merchandiseSyncInput.setMid(mid);
		merchandiseSyncInput.setCategoryCode(categoryCode);
		merchandiseSyncInput.setPageNo(Integer.toString(pageIndex));
		MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient
				.post(merchandiseSyncInput, "/product/merchandise",
						MerchandiseSyncOutput.class);

		List<Merchandise> productListTemp = merchandiseSyncOutput.getResult();
		if (productListTemp == null)
		{
			return null;
		}
		List<ErpProduct> productList = new ArrayList<ErpProduct>();
		// 处理价格分-元，图片路径
		for (Merchandise prt : productListTemp)
		{
			ErpProduct ep = new ErpProduct();
			ep.setId(prt.getProductId());
			ep.setCode(prt.getCode());
			ep.setName(prt.getName());
			ep.setPrice(prt.getPrice());
			ep.setShowMemPrice(prt.getMemberPrice());
			if ("".equals(prt.getPicUrl()))
			{
				ep.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else
			{
				ep.setPicUrl(Function.dealGridPicUrl(prt.getPicUrl(), 300, 300));
			}
			productList.add(ep);
		}
		return productList;
	}

	/**
	 * 进入餐点订单列表
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/myorders", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView myOrder(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest)
	{
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		if (StringUtils.isEmpty(cardId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		CateringSaleOrderListQueryInput input = new CateringSaleOrderListQueryInput();
		input.setCardId(cardId);
		input.setMid(mid);
		// input.setPageNo(pageNo);
		CateringSaleOrderListQueryOutput output = (CateringSaleOrderListQueryOutput) wizarposOpenRestClient
				.post(input, "/catering/saleorder/list/query",
						CateringSaleOrderListQueryOutput.class);
		if (output == null)
		{// 请求开放平台出错
			return new ModelAndView("error").addObject("err_message", "系统错误");
		}

		String code = output.getCode();
		if ("60001".equals(code))
		{// 60001非法慧商户号
			return new ModelAndView("error")
					.addObject("err_message", "该商户不存在。");
		} else if ("60070".equals(code))
		{// 60070 此商户下不存在此会员
			return new ModelAndView("redirect:/vip/receiveCard?mid=" + mid);// 前往会员卡领取页面
		} else if ("60037".equals(code))
		{// 60037非法的页码
			return new ModelAndView("error").addObject("err_message", "非法的页码");
		} else if (!SysConstants.OPEN_SUCCESS.equals(code))
		{// 60037非法的页码
			logger.error(output.getMessage());
			return new ModelAndView("error").addObject("err_message", "系统异常");
		}

		// 0 操作成功
		List<CateringSaleOrderDto> caterSaleOrderList = output
				.getSaleOrderList();

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();

		if (caterSaleOrderList.size() > 0)
		{
			for (CateringSaleOrderDto obj : caterSaleOrderList)
			{
				CateringReOrderView reOrderView = new CateringReOrderView();
				try
				{
					BeanUtils.copyProperties(reOrderView, obj);
				} catch (IllegalAccessException | InvocationTargetException e)
				{
					e.printStackTrace();
				}
				reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj
						.getShowOrderId()));
				reOrderView.setType("2");
				if ("0".equals(obj.getStatus()))
				{
					reOrderView.setStatus("1");
					orderList.add(reOrderView);
				} else
				{
					endedList.add(reOrderView);
				}
			}

			Collections.sort(orderList, new Comparator<CateringReOrderView>()
			{
				public int compare(CateringReOrderView a, CateringReOrderView b)
				{
					return b.getCreateTime().compareTo(a.getCreateTime());
				}
			});

			Collections.sort(endedList, new Comparator<CateringReOrderView>()
			{
				public int compare(CateringReOrderView a, CateringReOrderView b)
				{
					return b.getCreateTime().compareTo(a.getCreateTime());
				}
			});
		}
		return new ModelAndView("yuding/cymyorder")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList).addObject("mid", mid);
	}

	/**
	 * 进入餐点预订单列表
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 */
	@RequestMapping(value = "/myreorders", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView myReOrder(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest)
	{
		String cardId = (String) httpRequest.getSession().getAttribute(
				"mrtCardId");
		if (StringUtils.isEmpty(cardId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		CateringReOrderListQueryInput input = new CateringReOrderListQueryInput();
		input.setCardId(cardId);
		input.setMid(mid);
		// input.setPageNo(pageNo);
		CateringReOrderListQueryOutput output = (CateringReOrderListQueryOutput) wizarposOpenRestClient
				.post(input, "/catering/reorder/list/query",
						CateringReOrderListQueryOutput.class);
		if (output == null)
		{// 请求开放平台出错
			return new ModelAndView("error").addObject("err_message", "系统错误");
		} else if ("60001".equals(output.getCode()))
		{// 60001非法慧商户号
			return new ModelAndView("error")
					.addObject("err_message", "该商户不存在。");
		} else if ("60070".equals(output.getCode()))
		{// 60070 此商户下不存在此会员
			return new ModelAndView("redirect:/vip/receiveCard?mid=" + mid);// 前往会员卡领取页面
		} else if ("60037".equals(output.getCode()))
		{// 60037非法的页码
			return new ModelAndView("error").addObject("err_message", "非法的页码");
		}
		// 0 操作成功
		List<CateringReOrderDto> caterOrderList = output.getOrderList();

		List<CateringReOrderView> orderList = new ArrayList<CateringReOrderView>();
		List<CateringReOrderView> endedList = new ArrayList<CateringReOrderView>();

		if (caterOrderList.size() > 0)
		{
			for (CateringReOrderDto obj : caterOrderList)
			{
				CateringReOrderView reOrderView = new CateringReOrderView();
				try
				{
					BeanUtils.copyProperties(reOrderView, obj);
				} catch (IllegalAccessException | InvocationTargetException e)
				{
					e.printStackTrace();
				}
				reOrderView.setShowOrderId(Function.getShowWxOrderNo(obj
						.getShowOrderId()));
				reOrderView.setType("1");
				if (obj.getAuditFlag() == null
						|| "0".equals(obj.getAuditFlag().toString()))
				{// 待接受
					reOrderView.setStatus("0");
					orderList.add(reOrderView);
				} else if ("2".equals(obj.getAuditFlag().toString()))
				{// 预约单拒绝
					reOrderView.setStatus("-1");
					endedList.add(reOrderView);
				} else if ("1".equals(obj.getAuditFlag().toString()))
				{// 预约单已接受
					if ("2".equals(obj.getStatus().toString())
							|| "3".equals(obj.getStatus().toString()))
					{// 已经取消或已结账
						reOrderView.setStatus("2");
						endedList.add(reOrderView);
					} else
					{
						reOrderView.setStatus("1");
						orderList.add(reOrderView);
					}
				}
			}

			Collections.sort(orderList, new Comparator<CateringReOrderView>()
			{
				public int compare(CateringReOrderView a, CateringReOrderView b)
				{
					return b.getCreateTime().compareTo(a.getCreateTime());
				}
			});

			Collections.sort(endedList, new Comparator<CateringReOrderView>()
			{
				public int compare(CateringReOrderView a, CateringReOrderView b)
				{
					return b.getCreateTime().compareTo(a.getCreateTime());
				}
			});
		}
		return new ModelAndView("yuding/cymyorder")
				.addObject("orderList", orderList)
				.addObject("endedList", endedList).addObject("mid", mid);
	}

	/**
	 * 进入呼叫
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tohujiao", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView toHujiao(
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception
	{
		String openId = (String) httpRequest.getSession()
				.getAttribute("openId");
		if (StringUtils.isEmpty(openId))
		{// session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/catering/tohujiao");
		tmpUrl.append("?mid=").append(mid);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient
				.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);
		if (jsOutput == null
				|| SysConstants.OPEN_ERROR.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode()))
		{
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else
		{
			Map<String, String> result = (Map<String, String>) jsOutput
					.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}

		return new ModelAndView("yuding/hujiao", data);
	}

	/**
	 * 查看餐桌是否可用
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/usable", method = RequestMethod.GET)
	@ResponseBody
	public boolean usable(
			@RequestParam(value = "tableId", required = true) String tableId,
			@RequestParam(value = "mid", required = true) String mid)
			throws Exception
	{
		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("tableId", tableId);

		JSONObject respJson = null;
		try
		{
			respJson = wPosHttpClient.postOpen("/catering/table/using", json);
		} catch (Exception e)
		{
			// 消息推送失败
			logger.error("餐桌状态查询失败，tableId：" + tableId);
			return false;
		}

		String code = respJson.getString("code");
		if ("0".equals(code))
		{
			boolean using = respJson.getJSONObject("result")
					.getBoolean("using");
			return !using;
		} else if ("60009".equals(code) || "60028".equals(code))
		{
			return false;
		}

		return true;
	}

	/**
	 * 查看预订单是否可用 AuditFlag=1 预约已经接受 Status=0 尚未开台
	 * 
	 * @param mid
	 * @param dateTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkYuding", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkYuding(
			@RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "mid", required = true) String mid)
			throws Exception
	{
		CateringOrderQueryInput input = new CateringOrderQueryInput();
		input.setMid(mid);
		input.setReOrderId(orderId);
		CateringOrderQueryOutput ouptut = (CateringOrderQueryOutput) wizarposOpenRestClient
				.post(input, "/catering/reorder/query",
						CateringOrderQueryOutput.class);

		List<TableOrder> tableOrderList = ouptut.getResult();
		if (tableOrderList.size() != 0
				&& "1".equals(tableOrderList.get(0).getAuditFlag())
				&& "0".equals(tableOrderList.get(0).getStatus()))
		{
			return true;
		}
		return false;
	}

	/**
	 * 商品搜索页面
	 * 
	 * @return
	 */
	@RequestMapping("/p_search")
	public String pSearch(HttpServletRequest request)
	{
		request.getSession().setAttribute("openId","ohWaItzZIY918IcipyAEzHCaQCF0");
		request.getSession().setAttribute("mid","100300010000009");
		return "/dgd_order/p_search";
	}

	/**
	 * 搜索
	 * 
	 * @param searchKey
	 * @return
	 */
	@RequestMapping(value="/doPSearch",method=RequestMethod.POST)
	@ResponseBody
	public Object doPSearch(@RequestParam String keyWord,@RequestParam String mid,
			HttpServletRequest request)
	{
		String openId = (String) request.getSession().getAttribute("openId");
		if (StringUtils.isEmpty(openId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}		
			
		MerchandiseSyncInput producthotInput = new MerchandiseSyncInput();
		producthotInput.setMid(mid);
		producthotInput.setName(keyWord);
		MerchandiseSyncOutput producthotOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(producthotInput,"/product/merchandise",MerchandiseSyncOutput.class);
		
		return producthotOutput;
	}

}
